package com.nbsaas.boot.script.ext.resource;

import com.nbsaas.boot.script.ext.apis.ScriptResource;
import com.nbsaas.boot.script.ext.domain.simple.ScriptSource;
import lombok.Setter;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class DatabaseScriptSource implements ScriptResource {

    @Setter
    private  DataSource dataSource;


    @Override
    public String getPrefix() {
        return "db:";
    }

    @Override
    public ScriptSource loadScript(String path) {
        if (dataSource == null) {
            throw new IllegalStateException("DataSource 未设置");
        }
        String actual = path.startsWith(getPrefix()) ? path.substring(getPrefix().length()) : path;
        String sql = "SELECT content,last_modified FROM script_store WHERE code = ?";
        try {
            ScriptSource result = new ScriptSource();
            try (Connection conn = dataSource.getConnection();
                 PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setString(1, actual);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    result.setScript(rs.getString("content"));
                    result.setTimestamp(rs.getLong("last_modified"));
                    return result;
                } else {
                    return null;
                }
            }
        }catch (Exception ignored){
        }
         return  null;
    }
}
